package org.autumn.netty;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

@Slf4j
public class NIOTest {
    public static void main(String[] args) throws IOException {

        // create server
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // bind port
        ssc.bind(new InetSocketAddress(8080));
        // config non block
        ssc.configureBlocking(false);
        // list channel
        ArrayList<SocketChannel> channels = new ArrayList<>();

        while (true) {
            // build connection
            log.info("wait connect ...");
            SocketChannel sc = ssc.accept();
            if (sc != null) {
                log.info("connected ... {} ", sc);
                sc.configureBlocking(false);
                channels.add(sc);
            }
            for (SocketChannel channel : channels) {
                ByteBuffer buffer = ByteBuffer.allocate(16);
                int read = channel.read(buffer);
                if (read != 0) {
                    buffer.flip();
                    log.info("msg :{}", StandardCharsets.UTF_8.decode(buffer));
                }
            }

        }
    }
}
